package com.ophiux.cs.api.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;

/**
 * 说明：解决前端跨域问题<br>
 * <h1>创 建 人: hehailong<br></h1>
 * 创建日期: 2018年10月30日 上午10:37:35<br>
 * 修改记录：
 */
@Configuration
public class CorsFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String method = ((HttpServletRequest) request).getMethod();
		HttpServletResponse res = (HttpServletResponse) response;
		String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		res.addHeader("host", host);
		res.addHeader("Access-Control-Expose-Headers", "Roleplay-Error-Code");
		res.addHeader("Access-Control-Allow-Origin", "http://192.168.6.34:8080");
		res.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
		res.addHeader("Access-Control-Allow-Credentials", "true");
		res.addHeader("Access-Control-Allow-Headers",
				"Origin, Content-Type, Accept, Authorization, x-requested-with, cache-control, Access-Control-Allow-Origin, Access-Control-Allow-Credentials, uuid");
		if (method.equals("OPTIONS")) {
			res.setStatus(HttpServletResponse.SC_OK);
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
	
	}
}